#include <boost/regex.hpp>

#include"xpath_static.h"
#include "tinyxml.h"
#include "user.h"

User::User( const TiXmlElement* pUserElement ) throw( utils::Exception )
{
	const char* czAttVal = NULL;

	czAttVal = pUserElement->Attribute( "name" );
	m_sName = czAttVal ? czAttVal : "";

	czAttVal = pUserElement->Attribute( "password" );
	m_sPassword = czAttVal ? czAttVal : "";

	czAttVal = pUserElement->Attribute( "allowed_commands" );
	m_sAllowedCommands = czAttVal ? czAttVal : "";

	Split( m_sAllowedCommands, "^([a-zA-Z]*);([a-zA-Z]*);([a-zA-Z]*);([a-zA-Z]*);([a-zA-Z]*);$" );

}

void User::Split( const std::string& sInput, const std::string& sRegex ) throw()
{

	const boost::regex rxExpression( sRegex );
	boost::smatch rxMatch;
	if ( regex_match( sInput, rxMatch, rxExpression ) )
	{
		m_setCommands.insert( rxMatch[1] );
		m_setCommands.insert( rxMatch[2] );
		m_setCommands.insert( rxMatch[3] );
		m_setCommands.insert( rxMatch[4] );
		m_setCommands.insert( rxMatch[5] );

	}

	else
	{
		std::cout << "Error matching Commands!" << std::endl;
		throw utils::Exception( "Can't match Database" );
	}

}

bool User::CheckAvailableCommands( const std::string& sCommand ) throw( utils::Exception )
{
    //TODO could be done in 1 line of code
	UserSet::iterator it = m_setCommands.find( sCommand );
	if( it == m_setCommands.end() )
	{
		return 0;
	}
	else
	{
		return 1;
	}

}

std::string User::GetName() const throw()
{
	return m_sName;
}

std::string User::GetPassword() const throw()
{
	return m_sPassword;
}

std::string User::GetAllowedCommands() const throw()
{
	return m_sAllowedCommands;
}

bool User::CheckPassword( std::string sInput ) const throw()
{
    //TODO could be done in 1 line of code :)
	if( m_sPassword == sInput )
	{
		return 1;
	}
	else
	{
		return 0;
	}

}

std::string User::GetAvailableCommands()
{
	std::stringstream ssFNs;
	for( UserSet::const_iterator cit = m_setCommands.begin();
	 cit != m_setCommands.end();
	 ++cit )
	{
		ssFNs << *cit << " ";
	}

	return ssFNs.str();

}
